package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")//属性文件中获取输出目录的路径
    private String outPutPath;

    //保存套餐信息
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        //获取数据插入后生成的id
        Integer id = setmeal.getId();
        setCheckGroupAndSetMeal(id, checkgroupIds);
        //将操作数据库之后的照片陆军缓存至Redis中
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
        //当添加套餐后需要生成静态页面
        generateMobileStaticHtml();
    }

    //生成静态界面
    public void generateMobileStaticHtml() {
        //生成静态界面之前所需的数据
        List<Setmeal> list = setmealDao.findAll();
        //生成套餐列表静态界面
        generateMobileSetmealListHtml(list);
        //生成套餐详情静态界面
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态界面
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map map = new HashMap<>();
        //为模板提供数据用于生成静态界面
        map.put("setmealList", setmealList);
        generteHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    //生成套餐详情静态页面
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map map = new HashMap();
            map.put("setmeal", setmealDao.findBySetMealId(setmeal.getId()));
            // 采用的模板 * 生成的文件的名字 *  插入的map集合中存储所需的数据
            generteHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

    //用于生成静态页面
    public void generteHtml(String templateName, String htmlPageName, Map map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map, out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        //对查询条件进行判空处理
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = null;
        if (queryString != null && queryString.length() > 0) {
            page = setmealDao.selectByCondition("%" + queryString + "%");
        } else {
            page = setmealDao.selectByCondition(queryString);
        }
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public Setmeal findById(Integer id) {

        return setmealDao.findById(id);
    }

    @Override
    public List findCheckGroupIdsBySetMealId(Integer id) {

        return setmealDao.findCheckGroupIdsBySetMealId(id);
    }

    //套餐编辑项
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //删除关联关系
        setmealDao.deleteAssociation(setmeal.getId());
        //向中间表插入数据
        this.setCheckGroupAndSetMeal(setmeal.getId(), checkgroupIds);
        //更新数据
        setmealDao.update(setmeal);
        //当添加套餐后需要生成静态页面
        generateMobileStaticHtml();
    }

    @Override
    public void delete(Integer id) {
        Long count = setmealDao.SelectCountBySetMealId(id);
        if (count > 0) {
            //表示该套餐有关联检查组
            throw new RuntimeException("该检查项关联检查组，无法删除！");
        } else {
            setmealDao.delete(id);
        }
    }

    @Override
    public List<Setmeal> getSetmeal() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findBySetmealId(Integer id) {
        return setmealDao.findBySetMealId(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    //中间表内插入数据
    public void setCheckGroupAndSetMeal(Integer id, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("setmeal_id", id);
                map.put("checkgroup_id", checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }
}
